package org.szgb.console.sys.dict.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.szgb.console.sys.dict.entity.SysDict;
import org.szgb.console.sys.dict.mapper.SysDictChildrenMapper;
import org.szgb.console.sys.dict.mapper.SysDictMapper;
import org.szgb.console.utils.Page;
import org.szgb.console.utils.UUIDUtil;

import java.util.List;

@Slf4j
@Service
public class SysDictService {
    private final SysDictMapper sysDictMapper;
    private final SysDictChildrenMapper sysDictChildrenMapper;

    @Autowired
    public SysDictService(SysDictMapper sysDictMapper, SysDictChildrenMapper sysDictChildrenMapper) {
        this.sysDictMapper = sysDictMapper;
        this.sysDictChildrenMapper = sysDictChildrenMapper;
    }

    @Transactional(readOnly = true)
    public SysDict get(String id) {
        return sysDictMapper.get(id);
    }

    @Transactional(readOnly = true)
    public List<SysDict> findList(SysDict sysDict) {
        if (sysDict != null && sysDict.getPageDto() != null) {
            Page<SysDict> page = new Page<>(sysDict.getPageDto());
            page.setFirst((page.getPageNo() - 1) * page.getPageSize());
            sysDict.setPage(page);
        }
        return sysDictMapper.findList(sysDict);
    }

    @Transactional(readOnly = true)
    public Integer getCount(SysDict sysDict) {
        return sysDictMapper.getCount(sysDict);
    }

    @Transactional()
    public void save(SysDict sysDict) {
        // 检查实体对象的ID是否为null，判断是否为新实体
        if (sysDict.getId() == null || sysDict.getId().isEmpty()) {
            // 对于新实体，设置创建者信息
            sysDict.setCreatedBy(sysDict.getUpdatedBy());
            // 添加UUID
            sysDict.setId(UUIDUtil.getUUID());
            // 执行插入操作
            sysDictMapper.insert(sysDict);
            // 返回成功插入的信息
        } else {
            // 执行更新操作
            sysDictMapper.update(sysDict);
        }
    }

    @Transactional
    public void delete(String ids) {
        sysDictMapper.delete(ids.split(","));
        sysDictChildrenMapper.deleteByDictId(ids.split(","));
    }
}
